﻿#include "SerialLogger.h"

#include <chrono>
#include <iostream>

inline double get_current_time_stamp()
{
    std::chrono::duration d = std::chrono::system_clock::now().time_since_epoch();
    return std::chrono::duration_cast<std::chrono::milliseconds>(d).count() / 1000.0;
}

SerialLogger::~SerialLogger() {}

SerialLogger::SerialLogger(const std::string& dev_name) : serial_port(io_service), dev_name(dev_name)
{
    serial_port.open(dev_name);
    // 设置波特率
    serial_port.set_option(boost::asio::serial_port::baud_rate(9600));
}

void SerialLogger::open(DataSaver* saver)
{
    unsigned char  str_buf[512];
    unsigned char  str_buf_temp[512];
    unsigned char* p = str_buf_temp;
    while (true)
    {
        int size = 0;
        for (; p - str_buf_temp < 512; p++)
        {
            std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();
            boost::asio::read(serial_port, boost::asio::buffer(p, 1));
            long long spend_miliseconds =
                    std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start_time).count();

            // 按换行分割
#ifdef USE_LINE_FEED_SPLIT
            if (*p == '\n')
            {
                *p = '\0';
                strcpy(str_buf, str_buf_temp);
                p = str_buf_temp;
                break;
            }
#endif  // 0
        // 按照接收时间分割
            if (spend_miliseconds >= 400)
            {
                unsigned char temp = *p;
                *p                 = '\0';
                size               = p - str_buf_temp;
                memcpy(str_buf, str_buf_temp, size);
                p    = str_buf_temp;
                *p++ = temp;
                break;
            }
        }

        // 输出时间戳
        std::string formatted_str = "[";
        char        buf[20];

        std::sprintf(buf, "%.3f", get_current_time_stamp());
        formatted_str += buf;
        formatted_str += +"]" + dev_name + ": ";

        for (int i = 0; i < size; i++)
        {
            char buf[8];
            sprintf(buf, "0x%02x, ", str_buf[i]);
            formatted_str += buf;
        }
        // 线程安全地打印输出
        {
            // std::unique_lock<std::shared_mutex> _lock(_mutex);
            // std::cout << formatted_str << std::endl;
            saver->operator<<(formatted_str);
        }
    }
}
